package com.tianyi.sfzy1.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtil {
//    private String endpoint = "oss-cn-beijing.aliyuncs.com";// 阿里云服务器OSS地址
//    private String accessKeyId = "LTAI5tAxAcj5PnxnuUjJwjHb";//自己的密钥
//    private String accessKeySecret = "YsLfBo8FeBS71buaQrB86oPJ6NknGW";//自己的密钥
//    private String bucketName = "tamako66";//自己的桶名
    private String endpoint = "oss-cn-beijing.aliyuncs.com";// 阿里云服务器OSS地址
    private String accessKeyId = "LTAI5tAxAcj5PnxnuUjJwjHb";//自己的密钥
    private String accessKeySecret = "YsLfBo8FeBS71buaQrB86oPJ6NknGW";//自己的密钥
    private String bucketName = "tamako66";//自己的桶名


    /*
    * 实现上传图片到OSS*/
    public String uploadFile(MultipartFile multipartFile) throws IOException {
        //获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        //避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = String.format("https://%s.%s/%s", bucketName, endpoint, fileName);

        //关闭OSSClient
        ossClient.shutdown();
        return url;//返回的是图片的url地址，可以直接访问
    }

}

